package com.pay.demo.tech.statemachine;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: demo
 * @description: 支付状态机上下文
 * @author: guoxh
 * @create: 2019-04-04 13:48
 **/
public class PayStateMachineContext {

    private String currentInstanceId;
    private Map<String, Object> currentInstance;

    public PayStateMachineContext(String instanceId, Object instance) {
        this.currentInstanceId = instanceId;
        currentInstance = new HashMap<>();
        this.currentInstance.put(instanceId, instance);
    }

    private static ThreadLocal<PayStateMachineContext> contextContainer = new ThreadLocal<PayStateMachineContext>() {
    };

    /**
     *  获取当前线程下的支付上下文
     * @param instanceId 实例Id
     * @param instance   实例
     * @return
     */
    public static PayStateMachineContext getInstance(String instanceId, Object instance) {
        PayStateMachineContext discountRefundStateMachineContext = contextContainer.get();
        if (discountRefundStateMachineContext == null) {
            discountRefundStateMachineContext = new PayStateMachineContext(instanceId, instance);
            contextContainer.set(discountRefundStateMachineContext);
        } else {
            discountRefundStateMachineContext.currentInstanceId = instanceId;
            discountRefundStateMachineContext.currentInstance.put(instanceId, instance);
        }
        return discountRefundStateMachineContext;
    }

    public String currentInstanceId() {
        return contextContainer.get() != null ? contextContainer.get().currentInstanceId : null;
    }

    public <T> T currentInstance(String instanceId) {
        return contextContainer.get() != null ? (T) contextContainer.get().currentInstance.get(instanceId) : null;
    }
}
